<?php

class calendar extends WikiPlugin
{

	function calendar()
	{
		$this->add_macro('calendar', 'outputcal');
		$this->accumulate('header', 'jquery', 'jquery');
		$this->accumulate('header', 'calendar', 'calendar_head');
		$this->add_ajax_handler('calendar', 'ajax');
	}

	function outputcal($params)
	{
		global $rewrite, $wiki;

		$daytime = intval(strtotime("last sunday", time()) / 60 / 60 / 24) + 1;

		return '
			<nopee>
			<form onsubmit="setCalDate($(\'#calendar_lookup\').val());return false;">
			<a href="#" onclick="gobak();return false;"><img src="' . $rewrite->get_link(array('page'=>'plugins/calendar/past.gif')) . '" alt="past" /></a>
			<a href="#" onclick="smallercal();return false;"><img src="' . $rewrite->get_link(array('page'=>'plugins/calendar/smaller.gif')) . '" alt="smaller" /></a>
			<input type="text" value="' . date('M j, Y') . '" class="caldatelookup" id="calendar_lookup" />
			<a href="#" onclick="biggercal();return false;"><img src="' . $rewrite->get_link(array('page'=>'plugins/calendar/bigger.gif')) . '" alt="bigger" /></a>
			<a href="#" onclick="gofwd();return false;"><img src="' . $rewrite->get_link(array('page'=>'plugins/calendar/future.gif')) . '" alt="future" /></a>
			</form>
			<div id="calendar" class="wikicalendar"></div>
			</nopee>
			<script type="text/javascript">
			var ajaxurl="' . $rewrite->get_link(array('special'=>'ajax')) . '";
			var today=' . $daytime . ';
			var wikipage="' . $wiki->page_name .'";
			</script>
			<!--script type="text/javascript" src="' . $rewrite->get_link(array('page'=>'plugins/calendar/calendar.js')) . '"></script-->
		';
	}

	function processdates($page, $searchable = false)
	{
		global $wiki, $rewrite, $session, $db;

	  $pagetext = $wiki->getrawpage($page, $pagerow, false);

	  $cachename = 'calendar-'. md5($page . ($searchable == false));
	  //$wiki->cache_off = true;
	  $cache = $wiki->get_cache($cachename);
	  if($cache == '' || $searchable) {
		  $regex = '/{{calendar(.*?)}}/sim';
		  if(preg_match($regex, $pagetext, $matches)) {
				if(preg_match_all('/^(.+?),(.+)$/m', $matches[1], $dates, PREG_SET_ORDER)) {
					foreach($dates as $date) {
						$eventtime = intval(strtotime($date[1]) / 60 / 60 / 24) + 1;
						if($searchable != false) {
							if(strpos(strtolower($date[2]), strtolower($searchable)) !== false) {
								if(isset($events[$date[2]]) && ($events[$date[2]] < $eventtime)) continue;
								$events[trim($date[2])] = $eventtime;
							}
						}
						else {
							$events[$eventtime][] = array($date[0], $date[2]);
						}
					}
				}
			}
			$wiki->add_cache($cachename, array('notsurewhythisneedstobehere', $page), $events);
		}
		else {
			$events = $cache;
		}

		return $events;
	}

	function outprocessdates($page, $events)
	{
		global $wiki, $rewrite, $session, $db, $mwconfig;

	  $pagetext = $wiki->getrawpage($page, $pagerow, false);

		ksort($events);

	  foreach($events as $dayevents) {
	  	foreach($dayevents as $event) {
	  		$newevents .= $event[0] . "\n";
	  	}
	  }

	  $regex = '/{{calendar(.*?)\n(.*?)}}/sim';
	  $pagetext = preg_replace($regex, "{{calendar\\1\n" . $newevents . '}}', $pagetext);

		$npage = $db->escape($wiki->normalize_str($page));
		$mins = $db->get_var("SELECT ((cast(unix_timestamp(now()) as signed integer) - cast(unix_timestamp(max(postdate)) as signed integer)) / 60) FROM {$mwconfig->db_tableprefix}pages WHERE pagename = '{$npage}';", 'row');
		$user = $db->get_var("SELECT author FROM {$mwconfig->db_tableprefix}pages WHERE pagename = '{$npage}' ORDER BY postdate DESC LIMIT 1;");
		if(($mins <= $mwconfig->minoredittime) && ($session->user_id == $user)) {
			$pageid = $db->get_var("SELECT id FROM {$mwconfig->db_tableprefix}pages WHERE pagename = '{$npage}' ORDER BY postdate DESC LIMIT 1;");
			$pagetext = $db->escape($pagetext);
			$qry = "UPDATE {$mwconfig->db_tableprefix}pages SET body = '{$pagetext}', postdate = NOW() WHERE id = '{$pageid}';";
			$db->query($qry);
			$wiki->clear_cache($page);
		}
		else {
//echo $pagetext;
	  	save_page($page, array(
	      'pagecontent' => $pagetext,
	      'changenote' => 'Todo ' . $todo . ' updated.',
	    ));
	  }
	}

	function datecell($intday, $events, $contentonly = false)
	{
		foreach((array)$events[$intday] as $event) {
			$evt++;
			$id = 'event_' . $intday . '_' . $evt;
			$ids[] = $id;
			$body .= '<a href="#" title="' . $event[1] . '" class="calevent" id="' . $id . '">' . $event[1] . "</a><br />\n";
		}

		$ts = $intday * 60 * 60 * 24;

		$istoday = date('Y-m-d') == date('Y-m-d', $ts);

		$result = '
				<div class="date" onclick="dayclick(\'' . $ts . '\');">
					<span class="month">' . strtolower(date('M', $ts)) . '</span>
					<span class="day">' . strtolower(date('j', $ts)) . '</span>
					<span class="year">' . strtolower(date('Y', $ts)) . '</span>
				</div>' . $body . '
		';
		if(!$contentonly) {
			$result = '
				<td class="day_' . strtolower(date('l', $ts)) . ($istoday ? ' today' : '') .'" id="day_' . $ts . '">
				' . $result . '
				</td>
			';
		}

		return $result;
	}

	function ajax()
	{
		switch ($_POST['action']) {
		case 'getweek': return $this->getweek($_POST['week']);
		case 'datetoweek': return $this->datetoweek();
		case 'dayinfo': return $this->dayinfo(intval($_POST['date']), $_POST['page']);
		case 'removeevent': return $this->removeevent(intval($_POST['date']), $_POST['event'], $_POST['page']);
		case 'addevent': return $this->addevent(intval($_POST['date']), $_POST['event'], $_POST['page']);
		}
	}

	function getweek($i)
	{
	  $page = $_POST['page'];
	  $events = $this->processdates($page);

		$output = '
		<table>
			<tr>
		';

		for($i = intval($_POST['week']); $i < intval($_POST['week']) + 7; $i ++) {
			$output .= $this->datecell($i, $events);
		}
		$output .= '
			</tr>
		</table>
		';
		$json = array_merge($_POST, array('output'=>$output));
		echo json_encode($json);
	}

	function datetoweek()
	{
		$dt = strtotime($_POST['date']);
		$page = $_POST['page'];

		if($dt === false) {
		  $events = $this->processdates($page, $_POST['date']);
		  if(count($events) > 0) {
		  	$dt = array_shift($events) * 60 * 60 * 24;
		  }
		  else {
		  	$dt = time();
		  }
		}

		$json = array_merge($_POST, array( 'week' => intval(strtotime("last sunday", $dt) / 60 / 60 / 24) + 1));
		echo json_encode($json);
	}

	function dayinfo($dt, $page)
	{
		global $session;

		echo "<div style=\"text-align:left;width:100%;\">";
		echo "<h2>" . date('F j, Y', $dt) . "</h2>";

		$events = $this->processdates($page);
		$events = $events[$dt/60/60/24];

		echo "<ul id=\"dayeventlist\">";
		foreach((array)$events as $event) {
			$eid = $dt . '_' . md5($event[1]);
			echo "<li id=\"{$eid}\">";
			if($session->is_auth()) {
				echo '<input type="checkbox" checked="checked" name="event[]" value="foo" onclick="removeevent(this.parentNode, \'' . $dt . '\', \'' . md5($event[1]) . '\');"/>';
			}
			echo $event[1];
			echo "</li>";
		}
		echo "</ul>";

		echo '<form onsubmit="addevent(\'' . $dt . '\', $(\'#newevent\').val());return false;"><input type="text" id="newevent"><input type="submit" value="New Event" /></form>';

		echo '<a href="#" onclick="closeday();return false;">close</a>';

		echo "</div>";
	}

	function removeevent($dt, $eventmd5, $page)
	{
		global $session;
		if($session->is_auth()) {
			$events = $this->processdates($page);
			foreach($events[$dt / 60 / 60 / 24] as $idx=>$event) {
				if(md5($event[1]) == $eventmd5) {
					unset($events[$dt / 60 / 60 / 24][$idx]);
				}
			}
			$this->outprocessdates($page, $events);
		}
		$json = array_merge($_POST, array('output'=>$this->datecell($dt / 60 / 60 / 24, $events, true)));
		echo json_encode($json);
	}

	function addevent($dt, $event, $page)
	{
		global $session;
		if($session->is_auth()) {
			$events = $this->processdates($page);
			$events[$dt / 60 / 60 / 24][] = array(date('Y-m-d', $dt) . ",{$event}", $event);
			$this->outprocessdates($page, $events);
			$eid = date('Ymd', $dt) . '_' . md5($event);
		}
		$json = array_merge($_POST, array('output'=>$this->datecell($dt / 60 / 60 / 24, $events, true), 'eventmd5'=>md5($event)));
//		echo '<script language="javascript" type="text/javascript">makeDayEvent("' . $dt . '", "' . $event . '", "' . md5($event) . '");</script>';
		echo json_encode($json);
	}

	function calendar_head()
	{
		global $rewrite, $wiki;

		return '
		<script type="text/javascript">var ajaxurl="' . $rewrite->get_link(array('special'=>'ajax')) . '";</script>
		<script type="text/javascript" src="' . $rewrite->get_link(array('page'=>'plugins/calendar/calendar.js')) . '"></script>
		<link rel="stylesheet" type="text/css" href="' . $rewrite->get_link(array('page'=>'plugins/gallery/lightbox.css')) . '" media="screen" />';
	}

	function jquery()
	{
		global $rewrite, $wiki;

		return '<script type="text/javascript" src="' . $rewrite->get_link(array('page'=>'js/jquery-1.2.2.min.js')) . '"></script>';
	}
}

?>
